package cn.wonhigh.o2o.openfire.plugins.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jivesoftware.admin.AuthCheckFilter;
import org.jivesoftware.openfire.XMPPServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.wonhigh.o2o.openfire.plugins.MessagePlugin;

/**
 * 接收微信消息的Servlet.
 * 
 * @author yu.jz
 * @date 2014-7-18 上午9:45:21
 * @version 0.1.0
 * @copyright yougou.com
 */
public class MessageServlet extends HttpServlet {

	private static final Logger LOG = LoggerFactory
			.getLogger(MessageServlet.class);

	private static final long serialVersionUID = 1L;
	private String serviceName = "message/sendmsg";
	private MessagePlugin sendMsgPlugin;
	private String default_account = "admin";

	@Override
	public void init(ServletConfig servletConfig) throws ServletException {
		super.init(servletConfig);
		sendMsgPlugin = (MessagePlugin) XMPPServer.getInstance()
				.getPluginManager().getPlugin("message");
		AuthCheckFilter.addExclude(serviceName);
	}

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		PrintWriter out = response.getWriter();

		String from = request.getParameter("from");
		String to = request.getParameter("to");
		String msg = request.getParameter("msg");
		if (null == from || "".equals(from)) {
			/*
			 * replyError("fromNotFound",response,out); return;
			 */
			from = default_account;
		}
		if (null == to || "".equals(to)) {
			replyError("toNotFound", response, out);
			return;
		}
		if (null == msg || "".equals(msg)) {
			replyError("msgNotFound", response, out);
			return;
		}
		try {
			LOG.info("sendmsg 接收请求  ==> " + msg);
			String back = sendMsgPlugin.sendMessage(from, to, msg);
			replyMessage(back, response, out);
		} catch (Exception e) {
			LOG.error("发送消息出现异常.", e);
			replyError(e.getMessage(), response, out);
		}

	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}

	@Override
	public void destroy() {
		super.destroy();
		AuthCheckFilter.removeExclude(serviceName);
	}

	private void replyMessage(String message, HttpServletResponse response,
			PrintWriter out) {
		response.setContentType("text/xml");
		out.println("<result>" + message + "</result>");
		out.flush();
	}

	private void replyError(String error, HttpServletResponse response,
			PrintWriter out) {
		response.setContentType("text/xml");
		out.println("<error>" + error + "</error>");
		out.flush();
	}
}
